package leetcode.code1499;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

/**
 * 
 * 开点线段树实现</br>
 * 
 * 执行用时：249 ms, 在所有 Java 提交中击败了5.63%的用户
 * 
 * 内存消耗：184 MB, 在所有 Java 提交中击败了5.63%的用户
 * 
 * 通过测试用例：66 / 66
 */
public class Solution implements IDebug {

	public int findMaxValueOfEquation(int[][] points, int k) {
		int ans = Integer.MIN_VALUE;
		int range = (int) 1e8;
		Node o = new Node(-range, range);
		Queue<Integer> queue = new LinkedList<>();
		for (int i = 0; i < points.length; i++) {
			int[] p = points[i];
			int x = p[0], y = p[1];
			while (!queue.isEmpty() && x - points[queue.peek()][0] > k) {
				queue.poll();
			}
			if (!queue.isEmpty()) {
				ans = Math.max(ans, x + y + o.query(points[queue.peek()][0], x));
			}
			o.init(x, y - x);
			queue.add(i);
		}
		return ans;
	}

	class Node {
		private int L, M, R;

		private Node Left, Right;

		public int max;

		public Node(int l, int r) {
			L = l;
			R = r;
			M = ((r - l) >> 1) + l;
			//
			max = Integer.MIN_VALUE;
		}

		public int query(int l, int r) {
			if (l == L && r == R) {
				return max;
			} else {
				int ans = Integer.MIN_VALUE;
				if (l <= M) {
					ans = left().query(l, Math.min(r, M));
				}
				if (M < r) {
					ans = Math.max(ans, right().query(Math.max(l, M + 1), r));
				}
				return ans;
			}
		}

		public void init(int x, int v) {
			if (L == R) {
				max = v;
			} else {
				if (x <= M) {
					left().init(x, v);
				} else {
					right().init(x, v);
				}
				max = Math.max(left().max, right().max);
			}
		}

		private Node left() {
			if (Left == null) {
				Left = new Node(L, M);
			}
			return Left;
		}

		private Node right() {
			if (Right == null) {
				Right = new Node(M + 1, R);
			}
			return Right;
		}

	}

	@Override
	public void debug4() {
		H.compare(-6, this.findMaxValueOfEquation(H.str2array1("[[-19,9],[-15,-19],[-5,-8]]"), 10));
		H.compare(26,
				this.findMaxValueOfEquation(H.str2array1("[[-19,-12],[-5,-18],[2,-2],[10,3],[11,-3],[13,17]]"), 13));
		H.compare(4, this.findMaxValueOfEquation(H.str2array1("[[1,3],[2,0],[5,10],[6,-10]]"), 1));
		H.compare(3, this.findMaxValueOfEquation(H.str2array1("[[0,0],[3,0],[9,2]]"), 3));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
//		int a = -19;
//		int b = -18;
//		System.out.println((a+b)/2);
//		System.out.println(((b-a)>>1)+a);
	}

}
